import 'package:dali_ng_pera/manager/dnp_cache_manager.dart';
import 'package:dali_ng_pera/page/widget/dnp_dotted_line_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:dali_ng_pera/page/certification/model/dnp_city_model.dart';

class DnpCityChoiceDialog extends StatefulWidget {
  final String? initialRegion;
  final String? initialProvince;
  final String? initialCity;
  final ValueChanged<DnpCitySelection>? onConfirm;
  
  const DnpCityChoiceDialog({super.key, this.initialRegion, this.initialProvince, this.initialCity, this.onConfirm});

  @override
  State<DnpCityChoiceDialog> createState() => _DnpCityChoiceDialogState();
}

class _DnpCityChoiceDialogState extends State<DnpCityChoiceDialog> {
  DnpCityResponseModel? _data;
  List<DnpRegionModel> _level1 = [];
  List<DnpRegionModel> _level2 = [];
  List<DnpRegionModel> _level3 = [];
  int _currentLevel = 1;
  int _selectedL1 = -1;
  int _selectedL2 = -1;
  int _selectedL3 = -1;
  String? _selectedRegion;
  String? _selectedProvince;
  String? _selectedCity;

  @override
  void initState() {
    super.initState();
    String cityJson = DnpCacheManager().getString("enchantment")??"{}";
    try {
      final dynamic decoded = jsonDecode(cityJson);
      if (decoded is Map<String, dynamic>) {
        _data = DnpCityResponseModel.fromJson(decoded);
        _level1 = _data?.syllables ?? [];
      }
    } catch (_) {
      _level1 = [];
    }
    // 应用外部传入的初始定位（若有）
    _applyInitialSelection();
    // 默认链路：若没有选择，则从第一级开始默认选中第一个并向下联动
    if (_level1.isNotEmpty) {
      _ensureDefaultsFromLevel1(forceL1: _selectedL1 < 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Container(
          width: 309,
          height: 454.59,
          padding: const EdgeInsets.symmetric(horizontal: 14),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/ic_identity_correct_bg.webp'),
              fit: BoxFit.fill,
            ),
          ),
          child: Column(
            children: [
              SizedBox(height: 66),
              Text(
                'Title',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF252630),
                ),
              ),
              SizedBox(height: 14),
              Container(
                width: 267,
                height: 271,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildHeaderBar(),
                    DnpHorizontalDottedLineWidget(
                      width: double.infinity,
                      height: 1,
                      color: Color(0xFFE4E4E4),
                      marginLeft: 14,
                      marginRight: 14,
                    ),
                    const SizedBox(height: 4),
                    Expanded(child: _buildList()),
                  ],
                ),
              ),
              SizedBox(height: 14),
              _buildBottomButton()
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomButton() {
    return Row(
      children: [
        Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                Get.back();
              },
              child: Container(
                width: double.infinity,
                height: 48,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Color(0xFFCFE6FF),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Text(
                  "Back",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF95A5B9),
                  ),
                ),
              ),
            )),
        const SizedBox(
          width: 9,
        ),
        Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                final DnpCitySelection selection = DnpCitySelection(
                  region: _selectedRegion,
                  province: _selectedProvince,
                  city: _selectedCity,
                );
                if (widget.onConfirm != null) {
                  widget.onConfirm!(selection);
                }
                Get.back();
              },
              child: Container(
                width: double.infinity,
                height: 48,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Color(0xFF1D4AC8),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Text(
                  "Confirm",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            )),
        const SizedBox(
          width: 13,
        ),
      ],
    );
  }

  Widget _buildHeaderBar() {
    final TextStyle labelStyle = TextStyle(
      fontSize: 14,
      color: const Color(0xFF252630),
      fontWeight: FontWeight.w500,
    );

    Widget buildTab(String label, bool active, VoidCallback onTap) {
      return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: onTap,
        child: Container(
          height: 32,
          width: double.infinity,
          alignment: Alignment.center,
          child: Text(
            label,
            style: labelStyle.copyWith(
              color: active ? const Color(0xFF1D4AC8) : const Color(0xFF252630),
            ),
          ),
        ),
      );
    }

    final String l1 = _selectedRegion ?? '地区';
    final String l2 = _selectedProvince ?? '省份';
    final String l3 = _selectedCity ?? '城市';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        buildTab(l1, _currentLevel == 1, () {
          setState(() {
            if (_level1.isNotEmpty) {
              _ensureDefaultsFromLevel1(forceL1: _selectedL1 < 0);
            }
            _currentLevel = 1;
          });
        }),
        const SizedBox(height: 7),
        buildTab(l2, _currentLevel == 2, () {
          if (_selectedL1 >= 0) {
            setState(() {
              _ensureDefaultsFromLevel2();
              _currentLevel = 2;
            });
          }
        }),
        const SizedBox(height: 7),
        buildTab(l3, _currentLevel == 3, () {
          if (_selectedL2 >= 0) {
            setState(() {
              // 若二级未选，兜底默认选中第一个
              _ensureDefaultsFromLevel2();
              _currentLevel = 3;
            });
          }
        }),
      ],
    );
  }

  Widget _buildList() {
    final List<DnpRegionModel> items;
    if (_currentLevel == 1) {
      items = _level1;
    } else if (_currentLevel == 2) {
      items = _level2;
    } else {
      items = _level3;
    }

    if (items.isEmpty) {
      return const SizedBox();
    }

    return ListView.separated(
      itemCount: items.length,
      separatorBuilder: (_, __) => const SizedBox(height: 8),
      itemBuilder: (context, index) {
        final DnpRegionModel item = items[index];
        final String title = item.beersheba ?? '';
        bool selected = false;
        if (_currentLevel == 1) {
          selected = index == _selectedL1;
        } else if (_currentLevel == 2) {
          selected = index == _selectedL2;
        } else if (_currentLevel == 3) {
          selected = index == _selectedL3;
        }

        return GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            if (_currentLevel == 1) {
              _onSelectLevel1(index, item);
            } else if (_currentLevel == 2) {
              _onSelectLevel2(index, item);
            } else {
              _onSelectLevel3(index, item);
            }
          },
          child: Stack(
            children: [
              Container(
                height: 44,
                padding: const EdgeInsets.symmetric(horizontal: 8),
                alignment: Alignment.center,
                child: Text(
                  title,
                  style: TextStyle(
                    fontSize: 14,
                    color: selected ? const Color(0xFF333333) : const Color(0xFF666666),
                    fontWeight: selected ? FontWeight.w500 : FontWeight.w400,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              if (selected)
                const Positioned(
                  left: 14,
                  right: 14,
                  top: 0,
                  child: DnpHorizontalDottedLineWidget(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xFFDBDBDB),
                  ),
                ),
              if (selected)
                const Positioned(
                  left: 14,
                  right: 14,
                  bottom: 0,
                  child: DnpHorizontalDottedLineWidget(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xFFDBDBDB),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  void _onSelectLevel1(int index, DnpRegionModel item) {
    setState(() {
      _selectedL1 = index;
      _selectedRegion = item.beersheba;
      _level2 = item.syllables ?? [];
      // 进入二级时，若未选择，默认选中第一个并联动三级
      if (_level2.isNotEmpty) {
        _selectedL2 = 0;
        _selectedProvince = _level2[0].beersheba;
        _level3 = _level2[0].syllables ?? [];
        if (_level3.isNotEmpty) {
          _selectedL3 = 0;
          _selectedCity = _level3[0].beersheba;
        } else {
          _selectedL3 = -1;
          _selectedCity = null;
        }
      } else {
        _selectedL2 = -1;
        _selectedProvince = null;
        _level3 = [];
        _selectedL3 = -1;
        _selectedCity = null;
      }
      _currentLevel = 2;
    });
  }

  void _onSelectLevel2(int index, DnpRegionModel item) {
    setState(() {
      _selectedL2 = index;
      _selectedProvince = item.beersheba;
      _level3 = item.syllables ?? [];
      // 进入三级时，若未选择，默认选中第一个
      if (_level3.isNotEmpty) {
        _selectedL3 = 0;
        _selectedCity = _level3[0].beersheba;
      } else {
        _selectedL3 = -1;
        _selectedCity = null;
      }
      _currentLevel = 3;
    });
  }

  void _onSelectLevel3(int index, DnpRegionModel item) {
    setState(() {
      _selectedL3 = index;
      _selectedCity = item.beersheba;
    });
  }

  void _applyInitialSelection() {
    if (_level1.isEmpty) return;
    final String? regionName = widget.initialRegion;
    final String? provinceName = widget.initialProvince;
    final String? cityName = widget.initialCity;

    if (regionName != null) {
      final int idx1 = _level1.indexWhere((e) => e.beersheba == regionName);
      if (idx1 >= 0) {
        _selectedL1 = idx1;
        _selectedRegion = _level1[idx1].beersheba;
        _level2 = _level1[idx1].syllables ?? [];
      }
    }

    if (_level2.isNotEmpty && provinceName != null) {
      final int idx2 = _level2.indexWhere((e) => e.beersheba == provinceName);
      if (idx2 >= 0) {
        _selectedL2 = idx2;
        _selectedProvince = _level2[idx2].beersheba;
        _level3 = _level2[idx2].syllables ?? [];
      }
    }

    if (_level3.isNotEmpty && cityName != null) {
      final int idx3 = _level3.indexWhere((e) => e.beersheba == cityName);
      if (idx3 >= 0) {
        _selectedL3 = idx3;
        _selectedCity = _level3[idx3].beersheba;
      }
    }

    if (_selectedL3 >= 0) {
      _currentLevel = 3;
    } else if (_selectedL2 >= 0) {
      _currentLevel = 2;
    } else if (_selectedL1 >= 0) {
      _currentLevel = 1;
    }
  }

  void _ensureDefaultsFromLevel1({bool forceL1 = false}) {
    if (_level1.isEmpty) return;
    if (forceL1 && _selectedL1 < 0) {
      _selectedL1 = 0;
      _selectedRegion = _level1[0].beersheba;
    }
    // 基于当前L1，准备L2并默认
    final DnpRegionModel l1Item = _level1[_selectedL1 >= 0 ? _selectedL1 : 0];
    _level2 = l1Item.syllables ?? [];
    if (_level2.isNotEmpty) {
      if (_selectedL2 < 0) {
        _selectedL2 = 0;
      }
      _selectedProvince = _level2[_selectedL2].beersheba;
      _level3 = _level2[_selectedL2].syllables ?? [];
      if (_level3.isNotEmpty) {
        if (_selectedL3 < 0) {
          _selectedL3 = 0;
        }
        _selectedCity = _level3[_selectedL3].beersheba;
      } else {
        _selectedL3 = -1;
        _selectedCity = null;
      }
    } else {
      _selectedL2 = -1;
      _selectedProvince = null;
      _level3 = [];
      _selectedL3 = -1;
      _selectedCity = null;
    }
  }

  void _ensureDefaultsFromLevel2() {
    // 若一级未选，先默认一级
    if (_selectedL1 < 0 && _level1.isNotEmpty) {
      _selectedL1 = 0;
      _selectedRegion = _level1[0].beersheba;
      _level2 = _level1[0].syllables ?? [];
    }
    if (_level2.isNotEmpty) {
      if (_selectedL2 < 0) {
        _selectedL2 = 0;
      }
      _selectedProvince = _level2[_selectedL2].beersheba;
      _level3 = _level2[_selectedL2].syllables ?? [];
      if (_level3.isNotEmpty) {
        if (_selectedL3 < 0) {
          _selectedL3 = 0;
        }
        _selectedCity = _level3[_selectedL3].beersheba;
      } else {
        _selectedL3 = -1;
        _selectedCity = null;
      }
    } else {
      _selectedL2 = -1;
      _selectedProvince = null;
      _level3 = [];
      _selectedL3 = -1;
      _selectedCity = null;
    }
  }
}

class DnpCitySelection {
  final String? region;
  final String? province;
  final String? city;

  DnpCitySelection({this.region, this.province, this.city});
}
